$import('common.config.userCustom.dashboardDataLoad');
$import('common.knowledge.leftMenu');
$import('common.knowledge.knowledgeDetail');
$import('itsm.portal.schedule');
$import('itsm.portal.voiceCard');
$import('common.security.defaultCompany');
$import('common.tools.scheduledTask.scheduledTask');
$import('common.security.xssUtil');
/**  
 * @fileOverview "我的首页面板管理"
 * @author QXY  
 * @description 我的首页面板管理
 * @version 1.0  
 */
var helpdeskPortal=function(){
	this.calendarLoad="0";
	this.calendarTaskDiv = $('#calendarTaskDiv');
	this.mark=true;
	//公共方法
	this.showData=function(tableId,postUrl,param,method,urlStr){
		
		$.post(postUrl,param,function(data){
			
			if(data!=null && data!="" && data.length>0){
				
				$(tableId).empty();
				
				var count=0;
				$.each(data,function(i,item){
					method(i,item,tableId);
					count++;
					if(count>7){
						if(urlStr!=null && urlStr!='')
						$(tableId).append("<tr><td colspan='3' align='right'><a href='"+urlStr+"'>["+i18n['more']+"]</a></td></tr>");
						return false;
					}
				});
			}
			else{
				$(tableId).empty();
			}
				
		});
		
	};
	
	//公共方法
	this.showDataBk=function(tableId,postUrl,param,method){
		

		$.post(postUrl,param,function(data){
			
			if(data!=null && data.data!=null && data.data!=""){
				
				$(tableId).empty();
				
				var count=0;
				$.each(data.data,function(i,item){
					
					method(i,item,tableId);
					
					count++;
					
					if(count>7){
						return false;
					}
				});
			}else{
				$(tableId).html('');
				$(tableId).append("<tr><td align='center'><span style='color:#999999;'>"+i18n.emptyrecords+"...</span></td></tr>");
			}
		});
	};


	//我的任务
	this.showMyTask=function(tableId){
		var date = new Date();
		var start = dateFormat( date );
		if ( date.getMonth() == 11 ) {
			date.setFullYear( date.getFullYear() + 1);date.setMonth(0);
		}else{date.setMonth( date.getMonth() + 1);}
		var end = dateFormat( date );
		
		showDataBk(tableId,'tasks!findMyTaskForRecently1.action',"taskQueryDto.owner="+userName
				+"&taskQueryDto.sidx=taskId&taskQueryDto.sord=desc"
				+"&taskQueryDto.startTime="+start+"&taskQueryDto.endTime="+end
				,showMyTaskMethod);
	};
	//我的任务Method
	this.showMyTaskMethod=function(i,item,tableId){
		var len = $(tableId).width()/7.5;
		var _taskTitle = common.config.userCustom.dashboardDataLoad.cutstr(item.title, Math.ceil(len));
		//$(tableId).append("<tr><td style='width:5px'><img src='../images/numbers/"+(i+1)+".gif' /></td><td style='padding-left:10px;' ><a onclick='javascript:portalShowMyTask("+item.taskId+",\""+tableId+"\")'>"+item.title+"</a></td></tr>");
		$(tableId).append("<tr><td style='width:5px'><img src='../images/numbers/"+(i+1)+".gif' /></td><td ><a onclick='javascript:portalShowMyTask1(\""+item.taskId+"\",\""+item.startTime+"\",\""+item.endTime+"\",\""+tableId+"\")'>"+_taskTitle+"</a></td></tr>");
	};
	//我的报表
	this.showStatements=function(tableId){
		$.post('report!exportHTML.action',"fileName=requestStatus_count_Statements",function(html){
			$(tableId).html(html);
		});
	};
	
	this.engineerBusyDegreeMethod=function(i,item,tableId){
		if(i>9){
			$(tableId).append("<tr><td style='width:5%'>("+(i+1)+")</td><td style='padding-left:10px;width:40%'>"+item.name+"</td><td style='width:15%'><a href=javascript:openRequestList(\'"+item.name+"\')>"+item.quantity+"</a></td><td style='width:40%;color:#000;background-color:"+item.bgColor+"'>"+item.busy+"</td></tr>");
		}else{
			$(tableId).append("<tr><td style='width:5%'><img src='../images/numbers/"+(i+1)+".gif' /></td><td style='padding-left:10px;width:40%'>"+item.name+"</td><td style='width:20%'><a href=javascript:openRequestList(\'"+item.name+"\')>"+item.quantity+"</a></td><td style='color:#000;background-color:"+item.bgColor+"'>"+item.busy+"</td></tr>");
		}
	};
	//公告
	this.showAffiche=function(tableId){
		
		var url="affiche!find.action?sidx=affStart&sord=desc";
		showDataBk(tableId,url,'afficheQueryDto.companyNo='+companyNo+'&afficheQueryDto.queryFlag=portal',showAfficheMethod);
		
	};
	//公告Method
	this.showAfficheMethod=function(i,item,tableId){
		var len =($(tableId).width() - 40)/11;
		var _affTitle = common.config.userCustom.dashboardDataLoad.cutstr(item.affTitle, Math.ceil(len));
		/*var _affTitle=item.affTitle;
		if(_affTitle!=null&&_affTitle.length>16){
			
			_affTitle=_affTitle.substring(0,16)+'...';
		}*/
		$(tableId).append("<tr><td style='width:5px'><img src='../images/numbers/"+(i+1)+".gif' /></td><td ><a onclick='javascript:portalShowAffiche("+item.affId+")'>"+_affTitle+"</a></td><td style='width:30%'>"+timeFormatterOnlyData(item.affStart)+"</td></tr>");
	};
	

	//即时消息
	this.showMyIM=function(tableId){
		var url="immanage!findPager.action?manageQueryDTO.receiveUsers="+userName+"&sidx=status&sord=sec";
		showDataBk(tableId,url,null,showMyIMmethod);
	};
	
	//即时消息
	this.showMyIMmethod=function(i,item,tableId){
		var len = $(tableId).width()/12;
		var _imTitle = common.config.userCustom.dashboardDataLoad.cutstr(item.title, Math.ceil(len));
		var imstatus=item.status;
		if(imstatus==1){//<td id='IM"+item.imId+"' style='width:15%;min-width:40px;'>("+i18n['label_im_readed']+")</td>
			$(tableId).append("<tr id='tabId_"+tableId+"'><td style='width:5px'><span class='icon-openEmail' title='"+i18n['label_im_readed']+"'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span></td><td style='padding-left:0px;width:65%'><a onclick='javascript:portalShowIm("+item.imId+","+imstatus+")'>"+_imTitle+"</a></td><td style=''>"+item.senderFullName+"</td></tr>");
		}else if(imstatus==2){//<td id='IM"+item.imId+"' style='width:15%;min-width:40px;'>("+i18n['label_im_replyed']+")</td>
			$(tableId).append("<tr id='tabId_"+tableId+"'><td style='width:5px'><span class='icon-send' title='"+i18n['label_im_replyed']+"'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span></td><td style='padding-left:0px;width:65%'><a onclick='javascript:portalShowIm("+item.imId+","+imstatus+")'>"+_imTitle+"</a></td><td style=''>"+item.senderFullName+"</td></tr>");
		}else{//<td id='IM"+item.imId+"' style='width:15%;min-width:40px;'>("+i18n['label_im_notRead']+")</td>
			$(tableId).append("<tr id='tabId_"+tableId+"'><td style='width:5px'><span class='icon-email' title='"+i18n['label_im_notRead']+"'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span></td><td style='padding-left:0px;width:65%'><a onclick='javascript:portalShowIm("+item.imId+","+imstatus+")'>"+_imTitle+"</a></td><td style=''>"+item.senderFullName+"</td></tr>");
		}
	};

	//打开请求详细
	this.portalShowRequestDetail=function(gr){
		var url="request!requestDetails.action?eno="+gr+"&random="+Math.random()*10+1;
		basics.tab.tabUtils.refreshTab(i18n['request_detail'],url);	
	} ;
	
	
	//打开知识详情
	this.portalShowKnowledge=function(id){
		var url="knowledgeInfo!showKnowledge.action?kid="+id;
		basics.tab.tabUtils.refreshTab(knowledgeDetails,url);	
	};
	
	//打开公告信息
	this.portalShowAffiche=function(id){
		var postUrl="affiche!findAfficheDTOById.action";
		var param="afficheDto.affId="+id;
		$.post(postUrl,param,function(afficheDto){
			// $('#calendarTask_taskId').text(eventObject.id);
			$('#portal_affTitle').text(common.security.xssUtil.html_code(afficheDto.affTitle));
			$('#portal_affContents').attr('style','word-warp:break-word;word-break:break-all');
			$('#portal_affContents').html(afficheDto.affContents);
			$('#portal_affStart').text(
					timeFormatterOnlyData(afficheDto.affStart));
			$('#portal_affEnd').text(
					timeFormatterOnlyData(afficheDto.affEnd));
			$('#portal_cerateTime').text(timeFormatter(afficheDto.affCreaTime));
			windows('afficheDiv',{width: 400,modal: true});
		});	
	};

	//打开即时消息
	this.portalShowIm=function(id,imstatus){
		if(imstatus===2){
		}else{
			$("#IM"+id).html("("+i18n['label_im_readed']+")");
		}
		var postUrl="immanage!findInstantmessageById.action";
		var param="imDTO.imId="+id;
		$.post(postUrl,param,function(imDTO){
			$('#im_sendUser').text(imDTO.sendUsers);
			$('#im_sendTime').text(
					timeFormatter(imDTO.sendTime));
			$('#im_title').text(imDTO.title);
			var content='';
			if(imDTO.sendUsers=='system' && imDTO.eventType.indexOf("TaskDTO")<0){
				content='<a onclick=look_Details("'+imDTO.eventType+'",'+imDTO.requestEno+','+imDTO.imId+',"lookMessageDiv") >'+imDTO.content+'</a>';
			}else{
				content=imDTO.content;
			}
			$('#im_content').html(content);
			
			if (imDTO.status == '0') {
				$('#im_stats').text(i18n['label_im_notRead']);
			}
			if (imDTO.status == '1') {
				$('#im_stats').text(i18n['label_im_readed']);
			}
			if (imDTO.status == '2') {
				$('#im_stats').text(i18n['label_im_replyed']);
			}
			
			windows('lookMessageDiv',{width: 400,modal:true});
			if(imDTO.status=='0'){
				$.post('immanage!update.action','imDTO.imId='+imDTO.imId+'&imDTO.status=1',function(){
					$('#IMjqGrid').trigger('reloadGrid');
				});
				if(messageSize==1){
					stopBlinkNewMsg();
				}
				messageSize-=1;
			}
		});
		
		
	};
	this.portalShowMyTask1=function(taskId,start,end,tableId){
		itsm.portal.costCommon.scheduleShow1(taskId,start,end);
	};
	//我的任务
	this.portalShowMyTask=function(id,tableId){
		var postUrl="tasks!findByTaskId.action";
		var param="taskId="+id;
		$.post(postUrl,param,function(taskDto){
			$("#addcalendarTreatmentResultsTr").attr("style","display:none;");
			itsm.portal.schedule.historyShow(id);
			$('#schedule_task_process_but').show();
			$('#schedule_task_closed_but').show();
			$('#schedule_task_remark_but').show();
			$('#schedule_task_delete_but').show();
			$('#schedule_task_edit_but').show();
			$('#calendarResults_tr').hide();
			$('#calendarTask_taskId').val(id);
			$('#calendarTaskTitle').text(taskDto.title);
			$('#calendarTaskLocation').text(taskDto.location);
			$('#calendarTaskIntroduction').text(taskDto.introduction);
			$('#calendarTaskCreator').text(taskDto.creator);
			$('#calendarTaskOwner').text(taskDto.owner);
			$('#calendarTaskStartTime').text(timeFormatter(taskDto.startTime));
			$('#calendarTaskEndTime').text(timeFormatter(taskDto.endTime));
			$('#calendarRealStartTime').text(taskDto.realStartTime);
			$('#calendarRealEndTime').text(taskDto.realEndTime);
			$('#calendarRealFree').text(Math.floor(taskDto.realFree*1/1440)+i18n.label_slaRule_days+" "+Math.floor(taskDto.realFree*1%1440/60)+i18n.label_slaRule_hours+" "+Math.floor(taskDto.realFree*1%1440%60)+i18n.label_slaRule_minutes);
			if (taskDto.taskStatus == '0') {
				$('#calendarTaskStatus').text(i18n['title_newCreate']);
				$('#schedule_task_closed_but').hide();
			}
			if (taskDto.taskStatus == '1') {
				$('#calendarTaskStatus').text(i18n['task_label_pending']);
				$('#schedule_task_process_but').hide();
			}
			if (taskDto.taskStatus == '2') {
				$('#calendarTaskStatus').text(i18n['lable_complete']);
				$('#schedule_task_process_but').hide();
				$('#schedule_task_closed_but').hide();
				$('#calendarResults_tr').show();
				$('#calendarResults').text(taskDto.treatmentResults);
			}
			if (taskDto.allDay == 'true' || taskDto.allDay) {
				$('#calendarTaskAllDay').text(i18n['label_basicConfig_deafultCurrencyYes']);
			} else {
				$('#calendarTaskAllDay').text(i18n['label_basicConfig_deafultCurrencyNo']);
			}
			if(taskDto.ownerLoginName!=userName){
				$('#schedule_task_process_but').hide();
				$('#schedule_task_closed_but').hide();
				
			}
			if(taskDto.taskCreator==userName || operationTaskRes){
			}else{
				$('#schedule_task_delete_but').hide();
				$('#schedule_task_edit_but').hide();
			}
			$('#schedule_task_edit_but').unbind().click(function(){editCalendarTask(id,tableId);});
			$('#schedule_task_delete_but').unbind().click(function(){remoreCalendarTask(id,tableId);});
			$('#schedule_task_process_but').unbind().click(function(){processCalendarTask(id,tableId);});
			$('#schedule_task_closed_but').unbind().click(function(){closedCalendarTask_opt(id,tableId);});
			$('#schedule_task_remark_but').unbind().click(function(){remarkCalendarTask_opt(id,tableId);});
			windows('calendarTaskDiv',{width:600,modal: true});
		});
	};
	this.processCalendarTask=function(id,tableId){
		var _url="tasks!editTaskDetail.action";
		$.post(_url,'taskDto.taskId='+id+"&taskDto.taskStatus="+1+"&taskDto.operator="+userName,function(){
			calendarTaskDiv.dialog('close');
			$("#taskGrid").trigger('reloadGrid');
			msgShow(i18n.lable_startProcess,"show");
			portalShowMyTask(id,tableId);
		});
	};
	
	this.closedCalendarTask_opt=function(id,tableId){
		$.post("tasks!taskRealTimeDefaultValue.action",'taskId='+id,function(taskDto){
			calendarTaskDiv.dialog('close');
			resetForm("#realProcessTaskfm");
			$('#schedule_process_taskId').val(id);
			$('#schedule_process_realStartTime').val(taskDto.realStartTime);
			$('#schedule_process_realEndTime').val(taskDto.realEndTime);
			$('#schedule_process_taskCostDay').val(Math.floor(taskDto.realFree*1/1440));
			$('#schedule_process_taskCostHour').val(Math.floor(taskDto.realFree*1%1440/60));
			$('#schedule_process_taskCostMinute').val(Math.floor(taskDto.realFree*1%1440%60));
			$("#schedule_process_realFree").val(taskDto.realFree);
			//bindControl('#schedule_process_realEndTime,#schedule_process_realStartTime');
			$('#schedule_link_task_closedTask').unbind().click(function(){closedCalendarTask(tableId);});
			windows('realProcessTaskDiv',{width:600});
		});
	};

	this.closedCalendarTask=function(tableId){
		var _url="tasks!closedTaskDetail.action";
		if ($('#realProcessTaskfm').form('validate')) {
			var _param=$('#realProcessTaskDiv form').serialize();
			if(($('#schedule_process_realEndTime').val()!="" && $('#schedule_process_realStartTime').val() != "" && $('#schedule_process_realFree').val()>=1)){
				startProcess();
				$.post(_url,_param+"&taskDto.taskStatus="+2,function(){
					calendarTaskDiv.dialog('close');
					$("#taskGrid").trigger('reloadGrid');
					msgShow(i18n.lable_process_closedTask,"show");
					$('#realProcessTaskDiv').dialog('close');
					var taskId = $('#schedule_process_taskId').val();
					portalShowMyTask(taskId,tableId);
					endProcess();
				});
			}else{
				msgAlert(i18n.labe_taskClosedMsg,'info');
			}
		}
		
	};
	
	this.remarkCalendarTask_opt=function(id,tableId){
		var styleDisplay = $("#addcalendarTreatmentResultsTr").css("display");
		if (styleDisplay === "none") {
			$("#addcalendarTreatmentResultsTr").show();
			$("#schedule_link_task_remarkTask").unbind().click(function(){remarkCalendarTask(id,tableId);});
		}else{
			$("#addcalendarTreatmentResultsTr").hide();
		}
	};
	
	this.remarkCalendarTask=function(id,tableId){
		var _url="tasks!remarkTaskDetail.action";
		var treatmentResults = $("#addcalendarTreatmentResults").val();
		startProcess();
		$.post(_url,'taskDto.taskId='+id+"&taskDto.treatmentResults="+treatmentResults+"&taskDto.operator="+userName,function(){
			$("#addcalendarTreatmentResultsTr").attr("style","display:none;");
			$("#addcalendarTreatmentResults").val("");
			calendarTaskDiv.dialog('close');
			portalShowMyTask(id,tableId);
			endProcess();
		});
	};
	
	//编辑任务
	this.editCalendarTask=function(id,tableId){
		startLoading();
		$.post("tasks!findByTaskId.action",'taskId='+id,function(res){
			endLoading();
			calendarTaskDiv.dialog('close');
			//$("#scheduledSaskStatusTr").removeAttr("style");
			bindControl('#schedule_realEndTime,#schedule_realStartTime');
			opt='editTask';
			$('#schedule_link_task_save_edit_ok').show();
			$('#schedule_link_task_save_edit_ok2').show();
			if(res.taskStatus=='0'){
				$('#schedule_new').attr("checked",'true');
			}else if(res.taskStatus=='1'){
				$('#schedule_processing').attr("checked",'true');
			}else{
				$('#schedule_complete').attr("checked",'true');
			}
			
			if(res.allDay){
				$('#schedule_taskAllDay').attr("checked",true);
			}else{
				$('#schedule_taskAllDay').attr("checked","");
			}
			$("#schedule_task_taskId").val(res.taskId);
			if(res.title!=null && res.title!="null"){
				$("#schedule_taskTitle").val(res.title.substr(res.title.indexOf(']')+1));
			}else{
				$("#schedule_taskTitle").val("null");
			}
			$("#schedule_taskLocation").val(res.location);
			$("#schedule_taskIntroduction").val(res.introduction);
			$("#schedule_taskStartTime").val(res.startTime);
			$('#schedule_realStartTime').val(res.realStartTime);
			$('#schedule_realEndTime').val(res.realEndTime);
			$("#schedule_realFree").val(res.realFree);
			$('#schedule_taskCostDay').val(Math.floor(res.realFree*1/1440));
			$('#schedule_taskCostHour').val(Math.floor(res.realFree*1%1440/60));
			$("#schedule_taskCostMinute").val(Math.floor(res.realFree*1%1440%60));
			$('#schedule_treatmentResults').val(res.treatmentResults);
			$("#schedule_task_creator").val(res.taskCreator);
			$("#schedule_task_owner").val(res.ownerLoginName);
			$("#schedule_task_owner_fullName").val(res.owner);
			if(res.endTime!==null){
				$("#schedule_taskEndTime").val(res.endTime);}
			else{
				$("#schedule_taskEndTime").val(res.startTime);}
			$('#schedule_task_owner_link').unbind().click(function(){
				common.security.userUtil.selectUser('#schedule_task_owner','','','loginName',companyNo,'');
				});//选择技术员
			$('#schedule_link_task_save_edit_ok2').hide();
			$('#schedule_link_task_save_edit_ok').unbind().click(function(){saveTask(tableId);});

			windows('scheduleAddEditTaskDiv',{width:600});
		});
	};
	
	this.saveTask=function(tableId){
		startLoading();
		validateUsersByLoginName(
				$('#schedule_task_owner').val(),
				$("#schedule_task_owner_fullName").val(),
				function(){
				var title = $('#schedule_taskTitle').val();
				$('#schedule_taskTitle').val($.trim(title));
				var title = $('#schedule_taskIntroduction').val();
				$('#schedule_taskIntroduction').val($.trim(title));
				if($('#scheduleTaskForm').form('validate')){
					var _param = $('#scheduleTaskForm').serialize();
					var _url='tasks!'+opt+'.action';
					$.post(_url,_param,function(ids){
						endLoading();
						$('#scheduleAddEditTaskDiv').dialog('close');
						$("#taskGrid").trigger('reloadGrid');
						msgShow(i18n.saveSuccess,'show');
						showMyTask(tableId);
					});
                }
		});
	};
	
	//删除任务
	this.remoreCalendarTask=function(id,tableId){
		msgConfirm(i18n.msg_msg,'<br/>'+i18n.msg_confirmDelete,function(){
			$.post("tasks!deleteTask.action",'taskIds='+id,function(){
				$("#taskGrid").trigger('reloadGrid');
				calendarTaskDiv.dialog('close');
				msgShow(i18n.deleteSuccess,'show');
				showMyTask(tableId);
			});
		});
	};
	
	/**
	 * @description 为tab点击绑定事件
	 */
	this.helpdeskPortalTabClick=function(){
        $('#helpdeskPortalTab').tabs({
            onSelect:function(title){
            	if(title==calendarTitle && calendarLoad=="0"){//日程表
            		itsm.portal.schedule.showSchedule();
            		calendarLoad="1";
            	}
            }  
        });
	};
	this.loadhelpdesk=function(viewId){
		var viewName=$("#divid_"+viewId).val();
		if(viewName==="变更过滤器"){
			$("#viewId").remove();
			common.config.userCustom.dashboardDataLoad.findFilter(viewId,viewId);
		}
	};
	return{
		
		init:function(){
			//绑定日期控件
			DatePicker97(['#searchStartTime','#searchEndTime','#callShow_user_user_birthday']);
			
			$("#portal_loading").hide();
			$("#portal_content").show();
			//setTimeout(function(){helpdeskPortalTabClick();return false;},0);

			//bindControl('#schedule_taskEndTime,#schedule_taskStartTime');
			///setTimeout(function(){
				var $gallery = $(".lineTable");
				$("#helpdeskPortalTabid .column" ).sortable({
					connectWith: ".column",
					stop:function(event,ui){
						//拖动保存
						common.config.userCustom.dashboardDataLoad.saveLayout();
					}
				});
				$('#helpdeskPortalTabid .column').sortable('option', 'dropOnEmpty', true);
				$('#helpdeskPortalTabid .column').sortable({ handle: ".portlet-header" });
				$("#helpdeskPortalTabid .portlet" ).addClass( "ui-widget ui-widget-content ui-helper-clearfix" )
				.find( ".portlet-header" )
				.addClass( "ui-widget-header ui-corner-all" ).prepend( "<span class='ui-icon ui-icon-minusthick' style='cursor: pointer;'></span>")
				.end()
				.find( ".portlet-content" );
				 $(".portlet-header .ui-icon" ).click(function() {
					 $( this ).toggleClass( "ui-icon-minusthick" ).toggleClass( "ui-icon-plusthick" );
					 $( this ).parents( ".portlet:first" ).find( ".portlet-content" ).toggle();
				});
				$( "#helpdeskPortalTabid .column" ).disableSelection();
				
				//加载面板数据
					common.config.userCustom.dashboardDataLoad.loadDashboardData('');
			//},0);
			//windowResize.resizeItsmMainTab();
			
			setTimeout(function(){
				wstuo.dictionary.dataDictionaryUtil.loadOptionsByCode('taskType','#schedule_type');
				wstuo.dictionary.dataDictionaryUtil.loadOptionsByCode('taskType','#Task_type');
			},500);
		}
	};
}();
//载入

